﻿using System.Collections.Generic;
using System.Web.Mvc;
using System.Linq;
using WRSManagementSystem.DomainModel.Entities;
using WRSManagementSystem.DomainModel.Repositories;

namespace WRSManagementSystem.Controllers
{
    public class TypeController : Controller
    {
        private readonly ITypeRepository _typerepo;
        private readonly IUnitsRepository _unitsrepo;

        public TypeController(ITypeRepository typerepo, IUnitsRepository unitsrepo)
        {
            _typerepo = typerepo;
            _unitsrepo = unitsrepo;
        }

        //
        // GET: /Type/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Type/Create

        public ActionResult Create()
        {
            ViewData["Units"] = GetUnitsSelectList();
            return View(new Type());
        }

        //
        // POST: /Type/Create

        [HttpPost]
        public ActionResult Create(Type model)
        {
            ViewData["Units"] = GetUnitsSelectList();
            model.Unit = _unitsrepo.FindOne(u => u.Id == model.Unit.Id);

            if (ModelState.IsValid)
            {
                try
                {
                    // TODO: Add insert logic here
                    _typerepo.Add(model);
                    _typerepo.Save();
                    return RedirectToAction("Index", "StoreItem");
                }
                catch
                {
                    return View(model);
                }
            }
            return View(model);
        }

        private SelectList GetUnitsSelectList()
        {
            return new SelectList(_unitsrepo.Find(), "Id", "Name");
        } 
    }
}
